#!/usr/bin/env node

const figlet = require('figlet');
const fs = require("fs");
const chalk = require("chalk");
const { fontsSync } = require('figlet');
const inquirer = require("inquirer");


const {createFaviconIco,createPwaManifestFolder,createManiFestJson,createMoreRuleImage,createindexHtml,createStartPageHtml, startZip} = require('./libs');
const {getManifestTpl,getTplIndexHtml, getStartPageTplHtml} = require("./tpl");

chalk.level = 2;


/**
 * 获取颜色
 */
const getColor = () => {
  const COLORS = ["#e56045", "#ffb9b2", "#cc553d",
  "#53cfc8", "#a1e5e2", "#609996"];

  let colorKey = Math.floor(Math.random() * COLORS.length);
  return COLORS[colorKey];
}

/**
 * 获取版本 
 * @returns 
 */
const getVersion = () => {
  // package.json  
  let package = `${__dirname}/package.json`;
  if (fs.existsSync(package)) {
    let fileStr =fs.readFileSync(package);
    return JSON.parse(fileStr.toString()).version;
  } 
}


const showMenu = async () => {
  
  return await inquirer.prompt([{
    name: "menu",
    type: "list",
    message: "选择(menu)?",
    default: "测试工具",
    choices: ["测试工具", "json相关", "加密,解码,转换", "网络", "其它工具"],
  }])

}

const subMenu = async (menu) => {

  let submenu = "返回";
  switch (menu) {
    case "测试工具":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["在线post和get", "新版在线post和get", "API接口压力测试", "端口扫描", "其它工具", "返回"],
      }])
      break;
    case "json相关":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["最新的JSON格式化与压缩", "JSON转url参数"],
      }])
      break;
    case "加密,解码,转换":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["urlencode与urldecode转换", "sql/html/xml美化", "base64_encode与base64_decode转换", "formdata转url,kv", "md5加密"],
      }])
      break;

    case "加密,解码,转换":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["urlencode与urldecode转换", "sql/html/xml美化", "base64_encode与base64_decode转换", "formdata转url,kv", "md5加密", "unicode与中文互转"],
      }])
      break;
    case "网络":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["常用DNS", "order_useragent"],
      }])
      break;
    case "其它工具":
      submenu = await inquirer.prompt([{
        name: "menu",
        type: "list",
        message: "选择(menu) :",
        default: "测试工具",
        choices: ["两列对比差异", "时间戳转换", "随机字符串或密码生成", "在线nslookup", "图片base64转码", "base64转成图片", "markdown在线编辑","汉字转拼音"],
      }])
      break;

    default:

      break;
  }



  // console.log(submenu.menu, '<-----');
  // if (submenu.menu == '返回') {
  //   await showMenu();
  // } else {
    return submenu;
  // }
  
  
}


const setMenu = async ()=> {
  let menu = await showMenu();
  let submenu = await subMenu(menu.menu);
  if (submenu.menu == "返回") {
    submenu = await setMenu()
    console.log(submenu, '<-----3');
  } else {
    return submenu;
  }
  return submenu;
}

const getMenu = async () => {

  let menu = await setMenu()
  console.log(menu, '<-----menu1');
  console.log(menu, '<----2');
}



/**
 * 封面文字
 * @returns 
 */
const getFigletText = (text) => {

  const FONTS = ['Ghost', 'Crazy', 'Doom'];
  let font = FONTS[Math.floor(Math.random() * FONTS.length)];

  return new Promise((resolve, reject) => {
    figlet.text(`${text}`, {
      font: `${font}`,
      horizontalLayout: 'default',
      verticalLayout: 'default',
      width: 80,
      whitespaceBreak: true
    }, function(err, data) {
      if (err) {
          console.dir(err);
          reject(err);
          return;
      }
      resolve(data);
    });
  })
}


/**
 * 获取manifast命令参数 参数
 */
const getManifastConfigParam = async () => {
  return await inquirer.prompt([{
    name: "appName",
    type: "input",
    message: "请输入APP名称(name)?",
    default: "appName"
  },
  {
    name: "short_name",
    type: "input",
    message: "请输入APP简称(short_name)?",
    default: "short_name"
  },
  {
    name: "theme_color",
    type: "input",
    message: "主题颜色(theme_color)?",
    default: "#e56045"
  },
  {
    name: "background_color",
    type: "input",
    message: "默认背景(background_color)?",
    default: "#f2f2f2"
  },
  {
    name: "display",
    type: "list",
    message: "显示模式(display) :",
    default: "fullscreen",
    choices: ["fullscreen", "standalone", "minimal-ui", "browser"],
  },
  {
    name: "display",
    type: "list",
    message: "显示模式(display) :",
    default: "fullscreen",
    choices: ["fullscreen", "standalone", "minimal-ui", "browser"],
  },
  {
    name: "scope",
    type: "input",
    message: "范围(/) :",
    default: "/"
  },
  {
    name: "start_url",
    type: "input",
    message: "启动页面(/startpage.html) :",
    default: "/startpage.html"
  }]);


  
  
}




const getInquirerIcoParam = async () => {
  return await inquirer.prompt([
  {
    name: "icoRule",
    type: "list",
    message: "尺寸 (icoRule)?:",
    default: "16x16",
    choices: ["16x16", "32x32"],
  }]);

}



var argv = require('yargs')
  .option('p', {
    alias : 'image',
    demand: true,
    default: './favicon.png',
    describe: '图片',
    type: 'string'
})
.usage('Usage: tools [options] -p [path/img]')
  .example('tools manifast -p ./arrow.png', '生成manifast.json和相关文件')
  .example('tools zip', '打包成zip')
  .example('tools ico -p ./arrow.png', '生成favicon.ico')
  .help('h')
  .alias('h', 'help')
  .epilog('copyright 2021')
  .command("manifast", "生成manifast.json和相关文件",  async yargs => {

    //获取封面文字
    const text= await getFigletText('1902A');
    console.log(`\n${chalk.hex(`${getColor()}`)(text)}`);

    //获取版本
    let version = getVersion();
    console.log(`${chalk.bgBlue.white(' version ')}${chalk.bgRed.white(' '+version+' ')}\n\n`);

    //获取manifast会话
    const manifastConfigParam = await getManifastConfigParam()


    //创建一个目录 pwa-manifest
    await createPwaManifestFolder();
    //生成manifest.json
    const manifestTpl = getManifestTpl(manifastConfigParam);
    
    await createManiFestJson(manifestTpl)
    

    //生成不同尺寸的图片
    await createMoreRuleImage(yargs.argv.p)
    //生成模板 index.html
    let indexTpl = getTplIndexHtml();
    await createindexHtml(indexTpl)
    //启动页面 startPage.html
    let startPageTpl = getStartPageTplHtml();

    await createStartPageHtml(startPageTpl);
    // await createindexHtml(indexTpl)

  })
  .command("zip", "打成zip压缩包", function (yargs) {
    startZip()
  })
  .command("menu", "一级菜单", async function (yargs) {

    await getMenu();

    // subMenu
  })
  .command("ico", "生成favicon.ico",  async yargs=> {
    let icoParams = await getInquirerIcoParam();

    let arr = [{
      key: 16,
      value: '16x16'
    },{
      key: 32,
      value: '32x32'
    }];

    var icoParamObj = arr.filter(item =>item.value == icoParams.icoRule)
    icoKey= icoParamObj[0].key;

    //生成favicon.ico
    await createFaviconIco(icoKey, yargs.argv.p);

  })
  .argv;

